# for projects with multiple heroku apps, run like this with the app name:
#   rake heroku:clone_local["myappname"]

namespace :heroku do
  task :local_backup, [:heroku_app] => :environment do |t, args|
    Timeout.timeout(30.minutes) do
      if Rails.env.development?
        dump_folder = "#{Rails.root}/heroku_backups"
        FileUtils::mkdir_p dump_folder

        heroku_app_name = args[:heroku_app]
        if heroku_app_name.blank?
          app_option = ""
          dump_file = "#{dump_folder}/#{Date.today}.backup"
        else
          app_option = "--app #{heroku_app_name}"
          dump_file = "#{dump_folder}/#{heroku_app_name}_#{Date.today}.backup"
        end
        
        Bundler.with_clean_env do
          url_output = `heroku pg:backups public-url #{app_option}`

          backup_url = "\"" + url_output.strip + "\""

          puts backup_url

          puts "downloading last backup file"
          puts `curl -o #{dump_file} #{backup_url}`
        end
      else
        puts "only available in development environment"
      end
    end
  end

  task :clone_local, [:heroku_app] => :environment do |t, args|
    Timeout.timeout(30.minutes) do
      if Rails.env.development?
        dump_file = "latest.dump"
        local_host = "localhost"
        
        heroku_app_name = args[:heroku_app]
        if heroku_app_name.blank?
          app_option = ""
        else
          app_option = "--app #{heroku_app_name}"
        end
        
        local_user = `whoami`
        local_user.strip!
        
        dbname = YAML.load_file('config/database.yml')["development"]["database"]
        
        puts "running backup on heroku"
        Bundler.with_clean_env do
          capture_output = `heroku pg:backups capture #{app_option}`

          url_output = `heroku pg:backups public-url #{app_option}`

          backup_url = "\"" + url_output.strip + "\""

          puts "downloading dump file"
          puts `curl -o #{dump_file} #{backup_url}`
        end
        
        puts "dropping existing database schema"
        puts `psql -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public" -h #{local_host} -U #{local_user} -d #{dbname}`
        
        puts "restoring dump file to local"      
        puts `pg_restore --verbose --clean --no-acl --no-owner -h #{local_host} -U #{local_user} -d #{dbname} #{dump_file}`
        
        puts "deleting temporary dump file"
        puts `rm #{dump_file}`
        
        puts "migrating database"
        puts `skip_on_db_migrate=1 rake db:migrate`
        
        puts "changing passwords"

        User.order(:id).each do |user|
          user.password = "password"
          user.password_confirmation = "password"
          puts "could not change password for user #{user.id}: #{user.errors.full_messages.join(' ')}" if !user.save(validate: false)
        end

        puts "removing attachments"

        if User.new.respond_to?(:avatar)
          User.where("avatar_file_name IS NOT NULL").order(:id).each do |user|
            user.avatar = nil
            user.save!(validate: false)
          end
        end

        Company.all.each do |company|
          if company.respond_to?(:logo)
            company.logo = nil
            company.save!(validate: false)
          end
        end

      else
        puts "only available in development environment"
      end
    end
  end

end
